package com.kolakcc.loljclient.view.ui.renderer;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.border.EmptyBorder;

import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Mode;

import com.kolakcc.loljclient.model.XMPPWrapper;
import com.kolakcc.loljclient.util.StatusIcon;

public class FriendListItemRenderer implements ListCellRenderer<RosterEntry> {

	public Component getListCellRendererComponent(
			JList<? extends RosterEntry> list, RosterEntry value, int index,
			boolean isSelected, boolean cellHasFocus) {
		
		JPanel ret = new JPanel(new BorderLayout());
		ret.setOpaque(false);
		ret.setBorder(new EmptyBorder(0,0,5,0));
	    Presence p = XMPPWrapper.getConnection().getRoster().getPresence(value.getUser().split("/")[0]);
	    //System.out.println(p);
	    JLabel statusIconLabel = new JLabel(StatusIcon.getOffline());
	    statusIconLabel.setBorder(new EmptyBorder(0,5,0,5));
	    JLabel nameLabel = new JLabel(value.getName());
	    Font currentFont = nameLabel.getFont();
	    nameLabel.setFont(new Font(currentFont.getName(), Font.BOLD, currentFont.getSize()));
	    ret.add(nameLabel,BorderLayout.CENTER);
	    
	    String statusMsg = "<no message>";
	    if (p.getStatus() != null) {
	    	Matcher statusMatcher = Pattern.compile("<statusMsg>(.+?)</statusMsg>").matcher(p.getStatus());
		    while (statusMatcher.find()) {
		    	statusMsg = statusMatcher.group(1);
		    }
	    	Matcher gameStatusMatcher = Pattern.compile("<gameStatus>(.+?)</gameStatus>").matcher(p.getStatus());
		    while (gameStatusMatcher.find()) {
		    	switch (gameStatusMatcher.group(1)) {
		    		case "inGame": statusIconLabel.setIcon(StatusIcon.getInGame()); break;
		    		case "outOfGame": 
		    			if (p.getMode().equals(Mode.chat)) statusIconLabel.setIcon(StatusIcon.getAvailable());
		    			else if (p.getMode().equals(Mode.away)) statusIconLabel.setIcon(StatusIcon.getAway());
		    			break;
		    		case "inQueue": statusIconLabel.setIcon(StatusIcon.getInGame()); break;
		    	}
		    }
	    }
	    ret.add(statusIconLabel,BorderLayout.WEST);
	    if (!p.getType().equals(Presence.Type.unavailable)) {
		    JLabel statusLabel = new JLabel(statusMsg);
		    currentFont = statusLabel.getFont();
		    statusLabel.setFont(new Font(currentFont.getName(), Font.PLAIN, (int) (currentFont.getSize() * 0.7)));
		    statusLabel.setForeground(Color.DARK_GRAY);
		    ret.add(statusLabel,BorderLayout.SOUTH);
	    }
		return ret;
	}
}